package com.erik.ipmonitor.utils;


import java.util.Arrays;
import java.util.Collections;
import java.util.List;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.ListableBeanFactory;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.core.env.Environment;

/**
 * SpringContextUtil
 *
 * @author : erik.zhou
 * @date : 2025/07/09/15:56
 */
public class SpringContextUtil implements BeanFactoryPostProcessor, ApplicationContextAware {
    private static ConfigurableListableBeanFactory beanFactory;
    private static Environment environment = null;
    private static ApplicationContext applicationContext;

    public SpringContextUtil() {
    }

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        SpringContextUtil.beanFactory = beanFactory;
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ListableBeanFactory getBeanFactory() {
        return (ListableBeanFactory) (null == beanFactory ? applicationContext : beanFactory);
    }

    public static <T> T getBean(String name) {
        return (T) getBeanFactory().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return (T) getBeanFactory().getBean(clazz);
    }

    public static List<String> getActiveProfiles() {
        return null == applicationContext ? Collections.emptyList() : Arrays.asList(applicationContext.getEnvironment().getActiveProfiles());
    }

    public static String getProperty(String key) {
        if (environment == null) {
            environment = (Environment) getBean(Environment.class);
        }

        return environment.getProperty(key);
    }

    public static Environment getEnvironment() {
        return environment;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
}